<template>
  <view class="monitor">
    <view class="title">
      <text>实时监测</text>
    </view>
    <view id="mapDiv" class="mapDiv" ref="mapDiv"></view>
    <view class="map-type">
      <button size="mini" @tap="changeMapType('卫星')">卫星</button>
      <button size="mini" @tap="changeMapType('地图')">地图</button>
    </view>
    <view class="map-warning-level">
      <view class="level-item zc" @click="toggleShow('zc')">
        <image :src="icon_zc" />
        正常级{{enlarged?markers_zc.length:markers_zc.length/2}}个
        <image :src="showZC?icon_open:icon_close" />
      </view>
      <view class="level-item js" @click="toggleShow('js')">
        <image :src="icon_js" />
        警示级{{enlarged?markers_js.length:markers_js.length/2}}个
        <image :src="showJS?icon_open:icon_close" />
      </view>
      <view class="level-item jj" @click="toggleShow('jj')">
        <image :src="icon_jj" />
        警戒级{{enlarged?markers_jj.length:markers_jj.length/2}}个
        <image :src="showJJ?icon_open:icon_close" />
      </view>
      <view class="level-item jb" @click="toggleShow('jb')">
        <image :src="icon_jb" />
        警报级{{enlarged?markers_jb.length:markers_jb.length/2}}个
        <image :src="showJB?icon_open:icon_close" />
      </view>
    </view>
    <view class="dialog" v-show="showDialog" @click="showDialog=false">
      <view class="dialog-title">{{markerDetail.monitoringPositionName}}</view>
      <view class="dialog-content">
        预警级别：
        <span :class="className">{{markerDetail.prewarningLevelName}}</span>
      </view>
      <view class="dialog-content">
        灾害类型：
        <span class="blue">{{markerDetail.disasterTypeName}}</span>
      </view>
      <view class="dialog-content">
        位置：
        <span class="blue">{{markerDetail.gps}}</span>
      </view>
      <view class="dialog-content">
        方向：
        <span class="blue">无</span>
      </view>
      <view class="dialog-content">
        级别：
        <span class="blue">{{markerDetail.importance}}</span>
      </view>
    </view>
  </view>
</template>

<script>
import { loadModules } from "esri-loader";
import mapInfo from "./mapInfo";
export default {
  data() {
    return {
      map_type: "卫星",
      map: null, //地图对象
      view: null, //地图视图
      layer_base: null, //底图
      layer_anno: null, //道路位置信息
      layer_imagery: null, //全球影像
      layer_high: null, //区域高清影像,
      position_data: [], //地图点源数据
      markers_zc: [],
      markers_js: [],
      markers_jj: [],
      markers_jb: [],
      enlarged: true, //当前地图处于大图还是小图状态
      showDialog: false,
      markerDetail: {},

      icon_jb: require("../../asstes/image/ic_jbj.png"), //警报
      icon_jj: require("../../asstes/image/ic_jjj.png"), //警戒
      icon_js: require("../../asstes/image/ic_jsj.png"), //警示
      icon_zc: require("../../asstes/image/ic_zcj.png"), //正常

      showJB: true,
      showJJ: true,
      showJS: true,
      showZC: true,
      icon_open: require("../../asstes/image/ic_open.png"), //可见
      icon_close: require("../../asstes/image/ic_close.png") //不可见
    };
  },
  computed: {
    className() {
      return { "1": "jb", "2": "jj", "3": "js", "4": "zc" }[
        this.markerDetail.prewarningLevelID
      ];
    }
  },
  onLoad() {
    this.mapInit();
  },
  methods: {
    mapInit() {
      loadModules([
        "esri/Map",
        "esri/layers/support/TileInfo",
        "esri/views/MapView",
        "esri/layers/WebTileLayer",
        "esri/layers/TileLayer",
        "dojo/domReady!"
      ]).then(([Map, TileInfo, MapView, WebTileLayer, TileLayer]) => {
        const {
          TmapTileInfo,
          layer_base,
          layer_anno,
          layer_imagery,
          layer_high
        } = mapInfo;
        const tileInfo = new TileInfo(TmapTileInfo);

        this.layer_base = WebTileLayer(layer_base.url, {
          ...layer_base,
          tileInfo,
          visible: false
        });
        this.layer_anno = WebTileLayer(layer_anno.url, {
          ...layer_anno,
          tileInfo,
          visible: false
        });
        // 创建地图，不设置底图，如果设置底图会造成坐标系无法被转换成 ESPG:4326 (WGS1984)
        this.map = new Map({
          basemap: {
            baseLayers: [this.layer_base, this.layer_anno]
          }
        });
        this.layer_imagery = new TileLayer(layer_imagery);
        this.layer_high = new TileLayer(layer_high);
        this.map.addMany([this.layer_imagery, this.layer_high]);
        // 创建MapView
        this.view = new MapView({
          container: "mapDiv",
          spatialReference: {
            wkid: 4326
          },
          map: this.map,
          center: [103.9117594325, 33.1557136682],
          scale: 150000
        });
        this.view.when(
          () => {
            // All the resources in the MapView and the map have loaded. Now execute additional processes
            this.view.ui._removeComponents(["attribution", "zoom"]); //取消logo,隐藏放大缩小按钮
            console.log("ready!");
            this.bindPoint();
          },
          error => {
            // Use the errback function to handle when the view doesn't load properly
            console.log("The view's resources failed to load: ", error);
          }
        );
      });
    },
    bindPoint() {
      uni
        .request({
          url:
            "http://125.70.231.243:49527/monitoringPosition/getMonitoringPositions",
          method: "POST"
        })
        .then(([error, res]) => {
          if (res.data.state === 1) {
            this.position_data = res.data.data;
            this.getMarkers();

            this.view.on("click", event => {
              //marker点击
              this.view.hitTest(event).then(res => {
                const graphic = res.results.length && res.results[0].graphic;
                if (graphic && this.view.scale <= mapInfo.changeScale) {
                  //放大状态才绑定点击事件；
                  this.handleMarkerClick(graphic);
                }
              });
            });
            this.view.watch("stationary", isStationary => {
              //地图缩放
              if (
                isStationary &&
                this.view.scale <= mapInfo.changeScale &&
                this.enlarged
              ) {
                this.enlarged = false;
                this.getDetailMarkers();
              }
              if (
                isStationary &&
                this.view.scale > mapInfo.changeScale &&
                !this.enlarged
              ) {
                this.enlarged = true;
                this.getMarkers();
              }
            });
          }
        });
    },
    getMarkers() {
      loadModules(["esri/Graphic"]).then(([Graphic]) => {
        this.view.graphics.removeMany(this.markers_jb);
        this.view.graphics.removeMany(this.markers_jj);
        this.view.graphics.removeMany(this.markers_js);
        this.view.graphics.removeMany(this.markers_zc);
        this.markers_jb = [];
        this.markers_jj = [];
        this.markers_js = [];
        this.markers_zc = [];

        this.position_data.forEach(item => {
          if (item.gps) {
            const [latitude, longitude] = item.gps && item.gps.split(",");
            const url = {
              1: this.icon_jb,
              2: this.icon_jj,
              3: this.icon_js,
              4: this.icon_zc
            }[item.prewarningLevelID];
            const markerSymbol = {
              type: "picture-marker", // autocasts as new PictureMarkerSymbol()
              url,
              width: "36px",
              height: "36px"
            };
            const point = {
              //点位信息
              type: "point", // autocasts as new Point()
              longitude: longitude,
              latitude: latitude
            };
            switch (item.prewarningLevelID) {
              case "1": {
                this.markers_jb.push(
                  new Graphic({
                    geometry: point,
                    symbol: markerSymbol,
                    attributes: item
                  })
                );
                break;
              }
              case "2": {
                this.markers_js.push(
                  new Graphic({
                    geometry: point,
                    symbol: markerSymbol,
                    attributes: item
                  })
                );
                break;
              }
              case "3": {
                this.markers_jj.push(
                  new Graphic({
                    geometry: point,
                    symbol: markerSymbol,
                    attributes: item
                  })
                );
                break;
              }
              case "4": {
                this.markers_zc.push(
                  new Graphic({
                    geometry: point,
                    symbol: markerSymbol,
                    attributes: item
                  })
                );
                break;
              }
              default:
                break;
            }
          }
        });
        this.view.graphics.addMany(this.markers_zc);
        this.view.graphics.addMany(this.markers_js);
        this.view.graphics.addMany(this.markers_jj);
        this.view.graphics.addMany(this.markers_jb);
      });
    },

    getDetailMarkers() {
      loadModules(["esri/Graphic"]).then(([Graphic]) => {
        this.view.graphics.removeMany(this.markers_jb);
        this.view.graphics.removeMany(this.markers_jj);
        this.view.graphics.removeMany(this.markers_js);
        this.view.graphics.removeMany(this.markers_zc);
        this.markers_jb = [];
        this.markers_jj = [];
        this.markers_js = [];
        this.markers_zc = [];

        this.position_data.forEach(item => {
          if (item.gps) {
            const [latitude, longitude] = item.gps && item.gps.split(",");
            const url = {
              1: this.icon_jb,
              2: this.icon_jj,
              3: this.icon_js,
              4: this.icon_zc
            }[item.prewarningLevelID];
            const markerSymbol = {
              type: "picture-marker", // autocasts as new PictureMarkerSymbol()
              url,
              width: "36px",
              height: "36px"
            };
            const textSymbol = {
              type: "text", // autocasts as new TextSymbol()
              color: "white",
              text: item.monitoringPositionName,
              haloColor: [192, 192, 192, 0.3],
              haloSize: 3,
              xoffset: 15,
              yoffset: -9,
              horizontalAlignment: "left",
              font: {
                size: 12
              }
            };
            const point = {
              //点位信息
              type: "point", // autocasts as new Point()
              longitude: longitude,
              latitude: latitude
            };
            switch (item.prewarningLevelID) {
              case "1": {
                this.markers_jb.push(
                  new Graphic({
                    geometry: point,
                    symbol: markerSymbol,
                    attributes: item
                  })
                );
                this.markers_jb.push(
                  new Graphic({
                    geometry: point,
                    symbol: textSymbol,
                    attributes: item
                  })
                );
                break;
              }
              case "2": {
                this.markers_jj.push(
                  new Graphic({
                    geometry: point,
                    symbol: markerSymbol,
                    attributes: item
                  })
                );
                this.markers_jj.push(
                  new Graphic({
                    geometry: point,
                    symbol: textSymbol,
                    attributes: item
                  })
                );
                break;
              }
              case "3": {
                this.markers_js.push(
                  new Graphic({
                    geometry: point,
                    symbol: markerSymbol,
                    attributes: item
                  })
                );
                this.markers_js.push(
                  new Graphic({
                    geometry: point,
                    symbol: textSymbol,
                    attributes: item
                  })
                );
                break;
              }
              case "4": {
                this.markers_zc.push(
                  new Graphic({
                    geometry: point,
                    symbol: markerSymbol,
                    attributes: item
                  })
                );
                this.markers_zc.push(
                  new Graphic({
                    geometry: point,
                    symbol: textSymbol,
                    attributes: item
                  })
                );
                break;
              }
              default:
                break;
            }
          }
        });
        this.view.graphics.addMany(this.markers_zc);
        this.view.graphics.addMany(this.markers_js);
        this.view.graphics.addMany(this.markers_jj);
        this.view.graphics.addMany(this.markers_jb);
      });
    },
    goPoint(point, scale) {
      loadModules(["esri/geometry/Point"]).then(([Point]) => {
        const [latitude, longitude] = point.gps.split(",");
        this.view.goTo({
          target: new Point({
            latitude,
            longitude
          }),
          scale: scale
            ? scale
            : this.view.scale <= mapInfo.changeScale
            ? this.view.scale
            : mapInfo.changeScale
        });
      });
    },
    handleMarkerClick(graphic) {
      this.showDialog = true;
      this.markerDetail = graphic.attributes;
    },

    toggleShow(key) {
      switch (key) {
        case "zc": {
          if (this.showZC) {
            this.showZC = false;
            this.view.graphics.removeMany(this.markers_zc);
          } else {
            this.showZC = true;
            this.view.graphics.addMany(this.markers_zc);
          }

          break;
        }
        case "js": {
          if (this.showJS) {
            this.showJS = false;
            this.view.graphics.removeMany(this.markers_js);
          } else {
            this.showJS = true;
            this.view.graphics.addMany(this.markers_js);
          }
          break;
        }
        case "jj": {
          if (this.showJJ) {
            this.showJJ = false;
            this.view.graphics.removeMany(this.markers_jj);
          } else {
            this.showJJ = true;
            this.view.graphics.addMany(this.markers_jj);
          }
          break;
        }
        case "jb": {
          if (this.showJB) {
            this.showJB = false;
            this.view.graphics.removeMany(this.markers_jb);
          } else {
            this.showJB = true;
            this.view.graphics.addMany(this.markers_jb);
          }
          break;
        }
        default:
          break;
      }
    },

    changeMapType(type) {
      //切换地图
      if (type === this.map_type) {
        return;
      }
      this.map_type = type;
      switch (this.map_type) {
        case "卫星": {
          this.map.addMany([this.layer_imagery, this.layer_high]);
          this.map.basemap.baseLayers.forEach(item => {
            item.visible = false;
          });
          break;
        }
        case "地图": {
          this.map.removeMany([this.layer_imagery, this.layer_high]);
          this.map.basemap.baseLayers.items.forEach(item => {
            item.visible = true;
          });
          break;
        }
        default:
          break;
      }
    }
  }
};
</script>

<style scoped lang="scss">
uni-page-body {
  height: 100%;
  overflow: hidden;
}
.monitor {
  height: 100%;
  background-color: #f9f9f9;
  position: relative;
}

.title {
  font-size: 16px;
  padding: 15px;
  color: #fff;
  text-align: center;
  background: url("../../static/image/navbg.png") no-repeat center;
}
.mapDiv {
  width: 100%;
  height: 100%;
}
.map-type {
  position: absolute;
  right: 10rpx;
  top: 120rpx;
  z-index: 1000;
}
.map-warning-level {
  position: absolute;
  right: 10rpx;
  bottom: 20rpx;
  z-index: 1000;
  padding: 20rpx;
  background: url("../../static/image/bg_warning_level.png") no-repeat center;
  background-size: cover;
  .level-item {
    display: flex;
    align-items: center;
    margin: 10rpx;
    font-size: 28rpx;
    image {
      width: 36rpx;
      height: 36rpx;
      margin: 0 16rpx;
    }
  }
}
.dialog {
  position: absolute;
  right: 0;
  top: 0;
  left: 0;
  bottom: 0;
  z-index: 2000;
  background: url("../../static/image/bg_map_dialog.png") no-repeat center;
  background-size: cover;
  width: 540rpx;
  height: 480rpx;
  margin: auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  .dialog-title,
  .dialog-content {
    flex: 1;
    font-size: 24rpx;
    color: #fff;
  }
  .dialog-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #009ff1;
    text-align: center;
    padding: 20rpx 0;
  }
  .dialog-content {
    margin-left: 60rpx;
    margin-bottom: 20rpx;
  }
}
.zc {
  color: #00ff00;
}
.js {
  color: #ffff00;
}
.jj {
  color: #ff7f00;
}
.jb {
  color: #ff0000;
}
.blue {
  color: #009ff1;
}
</style>